package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/userInfo")
public class UserInfoServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 要判断是否登录
        HttpSession session = req.getSession(false);
        User user = null ;
        if(session == null || session.getAttribute("user") == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }
         // 判断当前是在详情页还是在列表页
           String blogId = req.getParameter("blogId");
           String respJson = null ;
           if(blogId == null){
              user = (User) session.getAttribute("user");
           }else{
               UserDao userDao = new UserDao();
               BlogDao blogDao = new BlogDao();
               Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
               user = userDao.getUserById(blog.getUserId());
           }
        // 注意保密, 在把user给 respJson之前,把password给处理了
           user.setPassword("");
           respJson = objectMapper.writeValueAsString(user);
           resp.setStatus(200);
           resp.setContentType("application/json; charset=utf8");
        System.out.println("用户名:"+respJson);
        resp.getWriter().write(respJson);
    }
}
